package com.amz.analyzer.exception.handler;

import cn.hutool.core.util.StrUtil;
import com.amz.analyzer.exception.AmzException;
import com.amz.analyzer.util.Result;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.java.Log;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * <p>
 * 描述: 公共异常处理
 * </p>
 *
 * @author Freddy
 * @version 1.0
 * @since 2020/7/12 14:41
 */
@Log
@RestControllerAdvice  // 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
public class ExceptionHandller {

    /**
     * 自定义异常处理
     *
     * @param e KsException
     * @return Result
     */
    // 统一处理一种类的异常，减少代码重复率，降低复杂度。
    @ExceptionHandler(value = AmzException.class)
    @ResponseBody
    public Result verifyKsException(AmzException e) {
        log.warning(StrUtil.format("异常：编码[{}]，{}", e.getCode(), e.getMessage()));
        Result<String> failure = Result.failure(e.getMessage(), e.getMessage());

        return failure;
    }

    /**
     * 参数验证异常处理
     *
     * @param e 异常对象
     * @return Result
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result verifyBindException(BindException e) {
        log.warning(StrUtil.format("异常：{}", e.getMessage()));
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();

        String[] messages = allErrors.parallelStream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage).toArray(String[]::new);

        Result<String> failure = Result.failure(StrUtil.join(StringPool.SEMICOLON, (Object[]) messages));
        return failure;
    }

}
